package mhnm.projectgoodmorning;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;

public class BTController extends Service {
	private BluetoothAdapter localAdapter = BluetoothAdapter.getDefaultAdapter();
	private BluetoothDevice btDevice;
	private BluetoothSocket btSocket;

	private final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private String currentMAC;

	private OutputStream outputStream;
	public OutputStream getOutputStream() {
		return outputStream;
	}
	
	private InputStream inputStream;
	public InputStream getInputStream() {
		return inputStream;
	}
	
	private boolean connected = false;
	public boolean isConnected() {
		return connected;
	}
	
    @Override
    public void onCreate() {
    	Toast.makeText(this, "BTService stated.", Toast.LENGTH_SHORT).show();
    	
    	super.onCreate();
    }
    
    @Override
    public void onDestroy() {
    	Toast.makeText(this, "BTService stoped.", Toast.LENGTH_SHORT).show();
    	
    	close();
    	
    	super.onDestroy();
    }
	
	public void connect( String deviceMAC ) throws IOException {
		currentMAC = deviceMAC;
		
		btDevice = localAdapter.getRemoteDevice( deviceMAC );
		btSocket = btDevice.createRfcommSocketToServiceRecord( uuid );

		btSocket.connect();
		
		outputStream = btSocket.getOutputStream();
		inputStream = btSocket.getInputStream();
		
		connected = true;
	}
	
	public void reConnect() throws IOException {
		if( currentMAC != null ) {
			connect( currentMAC);
		} else {
			throw new IllegalStateException( "No previous connection." );
		}
	}
	
    public void close() {
    	connected = false;
    	
    	if( btSocket != null ) {
			try {
				btSocket.close();
			} catch (IOException e) {
	
			}
    	}
    }
	
	public Set<BluetoothDevice> getBondedDevices() {
		return this.localAdapter.getBondedDevices();
	}
	
	public boolean isEnabled() {
		return localAdapter.isEnabled();
	}
	
	public void enable() {
		localAdapter.enable();
	}

	
    public class LocalBinder extends Binder {
    	BTController getService() {
            return BTController.this;
        }
    }		
	
	private final IBinder binder = new LocalBinder();
	@Override
	public IBinder onBind( Intent intent ) {
		return binder;
	}
}